package com.example.lottery.service.impl;

import com.example.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.example.lottery.common.exception.ServiceException;
import com.example.lottery.common.utils.CapthchaUtil;
import com.example.lottery.common.utils.RedisUtil;
import com.example.lottery.common.utils.RegexUtil;
import com.example.lottery.dao.dataobject.Encrypt;
import com.example.lottery.dao.mapper.UserMapper;
import com.example.lottery.service.IVerificationCodeService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CapthchaUtil capthchaUtil;
    @Autowired
    private RedisUtil redisUtil;

    private static final String VERIFICATION_CODE_PREFIX="VERIFICATION_CODE_";

    private static final Long Time=60l;
    @Override
    public void sendVerificationCode(HttpServletResponse response,String phoneNumber) {
        log.info("phoneNumber："+phoneNumber);
        //1-    校验手机号格式
        if(!RegexUtil.checkMobile(phoneNumber)){
            log.warn("手机号格式错误");
            throw new ServiceException(ServiceErrorCodeConstants.USER_PHONE_NUMBER_ERROR);
        }
        //2-    手机号是否存在
        if(userMapper.selectByPhoneNumberCount(new Encrypt(phoneNumber))!=1){
            log.warn("手机号不存在");
            throw new ServiceException(ServiceErrorCodeConstants.USER_PHONE_NUMBER_NOT_EXIST);
        }
        //3-    发送验证码
        String captcha = capthchaUtil.createCaptcha(response);
        log.info("生成的验证码："+captcha);
        //4-    存储验证码，并设置有效时间
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,captcha,Time);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //1-    校验手机号格式
        if(!RegexUtil.checkMobile(phoneNumber)){
            log.warn("手机号格式错误");
            throw new ServiceException(ServiceErrorCodeConstants.USER_PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
